//
//  AiChatConvertExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/11/4.
//


//ChatBean的一些数据转换
import Foundation
class AiChatConvertExt {
    
    static func dealChat(_ bean: ChatBean) async throws {
        //更新角色
        try await dealRole(bean)
        //处理引用内容
        try await dealTargetChat(bean)
        //处理拍一拍
        try await dealPat(bean)
    }
    
    //根据聊天，获取最新的RoleBean
    private static func getRole(_ bean: ChatBean?) async throws -> RoleBean? {
        if (bean == nil) { return nil }
        let role = bean?.role
        if role?.isBot() == true {
            //获取最新数据
            guard let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: role?.roleId ?? "") else { return nil }
            return RoleBean.get(aiRole)
        } else {
            bean?.role?.showName = userManager.getName()
            bean?.role?.avatar = userManager.getAvatar()
            bean?.role?.bubbleId = userManager.getExtraConfig().bubbleId
            bean?.role?.bubbleCommentId = userManager.getExtraConfig().bubbleCommentId
            return bean?.role
        }
    }
    
    private static func dealRole(_ bean: ChatBean?) async throws {
        if let bean = bean {
            bean.role = try await getRole(bean)
        }
    }
    
    /**
     * 处理引用内容
     */
    private static func dealTargetChat(_ bean: ChatBean?) async throws {
        guard let extra = bean?.extra else {
            return
        }
        guard let bean = bean, let quote = try? fromJson(extra, ChatMessageBean.Quote.self) else {
            //类型转换失败
            return
        }
        guard IChatContentType.TYPE_CONTENT_TARGET.rawValue == bean.contentType else {
            return
        }
        
        guard let targetId = quote.target_id, !targetId.isEmpty else {
            return
        }
        
        let targetChat = try await BackupsManager.shared.getDelegateDiary()?.queryChat(objectId: targetId)
        bean.targetChat = targetChat
        
    }
    
    /**
     * 处理拍一拍
     */
    private static func dealPat(_ bean: ChatBean?) async throws {
        guard let bean = bean, var pat = try? fromJson(bean.extra, ChatMessageBean.Pat.self) else {
            //类型转换失败
            return
        }
        guard IChatContentType.TYPE_ACTION.rawValue == bean.contentType else {
            return
        }
        
        //由于名称会被更改，所以在这边获取最新的名称
        pat.userName = pat.userId == userManager.getUserId() ? userManager.getName() : try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: pat.userId).name
        
        bean.extra = toJson(pat)
        
    }
}
